// util/ProbabilityUtils.java
package com.ruoyi.common.utils;

import java.util.*;

public class ProbabilityUtils {

    private static final List<String> ALL_CARDS = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H");

    public static Map<String, Integer> generateUnlockPlan(Map<String, Integer> limitation) {
        List<String> shuffled = new ArrayList<>(ALL_CARDS);
        Collections.shuffle(shuffled);
        Map<String, Integer> unlockPlan = new HashMap<>();

        List<Map.Entry<String, Integer>> sortedLimits = new ArrayList<>(limitation.entrySet());
        sortedLimits.sort(Comparator.comparingInt(Map.Entry::getValue));

        for (int i = 0; i < sortedLimits.size(); i++) {
            unlockPlan.put(shuffled.get(i), sortedLimits.get(i).getValue());
        }

        for (String card : ALL_CARDS) {
            unlockPlan.putIfAbsent(card, 0);
        }

        return unlockPlan;
    }

    public static String weightedDraw(List<String> validCards, Map<String, Double> probabilities) {
        double total = 0.0;
        for (String card : validCards) {
            Number orDefault = probabilities.getOrDefault(card, 0.0);
            total += orDefault.doubleValue();
        }

        double rand = Math.random() * total;
        double cumulative = 0.0;

        for (String card : validCards) {
            Number cardNumber = probabilities.get(card);
            cumulative +=cardNumber.doubleValue();
            if (rand <= cumulative) {
                return card;
            }
        }

        return validCards.get(0); // fallback
    }

    public static List<String> getAllCards() {
        return ALL_CARDS;
    }
}
